package com.ruoyi.order.service.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.order.domain.Coupon;
import com.ruoyi.order.mapper.CouponMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.UserCouponMapper;
import com.ruoyi.order.domain.UserCoupon;
import com.ruoyi.order.service.IUserCouponService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户优惠券关联Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-10
 */
@Service
public class UserCouponServiceImpl implements IUserCouponService 
{
    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 查询用户优惠券关联
     * 
     * @param ucId 用户优惠券关联主键
     * @return 用户优惠券关联
     */
    @Override
    public UserCoupon selectUserCouponByUcId(Long ucId)
    {
        return userCouponMapper.selectUserCouponByUcId(ucId);
    }

    /**
     * 查询用户优惠券关联列表
     * 
     * @param userCoupon 用户优惠券关联
     * @return 用户优惠券关联
     */
    @Override
    public List<UserCoupon> selectUserCouponList(UserCoupon userCoupon)
    {
        return userCouponMapper.selectUserCouponList(userCoupon);
    }

    /**
     * 新增用户优惠券关联
     * 
     * @param userCoupon 用户优惠券关联
     * @return 结果
     */
    @Override
    public R insertUserCoupon(UserCoupon userCoupon) {

        Coupon coupon = couponMapper.selectCouponByCId(userCoupon.getcId());
        if (coupon == null) {
            return R.fail("优惠券不存在");
        }

        Date now = new Date();
        if (now.after(coupon.getIssueEndTime()) || now.before(coupon.getIssueStartTime())) {
            return R.fail("不在抢券时间！");
        }

//        获取锁
        RLock lock = redissonClient.getLock("lock:order" + userCoupon.getcId());
        boolean isLock = lock.tryLock();

        if (!isLock) {
            return R.fail("未获取到锁");
        }else{
//            System.out.println("获取到锁");
            try {
                IUserCouponService proxy = (IUserCouponService) AopContext.currentProxy();
                return proxy.addCoupon(userCoupon, coupon);
            } catch (Exception e) {
                System.out.println("系统异常，领取失败");
                return R.fail("系统异常，领取失败");
            } finally {
//                释放锁
                if (isLock && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

    @Transactional
    public R addCoupon(UserCoupon userCoupon, Coupon coupon) {
        if (coupon.getTotalQuantity() < 1L) {
            System.out.println("优惠券数量不足");
            return R.fail("优惠券数量不足");
        }

        Long perUserLimit = coupon.getPerUserLimit();

        Long count = userCouponMapper.selectCountByUserIdAndCouponId(userCoupon.getuId(), userCoupon.getcId());

        if( perUserLimit != null && count >= perUserLimit){
            System.out.println("您领取该优惠券数量已达上限");
            return R.fail("您领取该优惠券数量已达上限");
        }

        //库存减一
        coupon.setTotalQuantity(coupon.getTotalQuantity() - 1L);
        int i = couponMapper.updateCoupon(coupon);
        if(i == 0){
            return R.fail("库存更新失败，抢券失败");
        }

        int i1 = userCouponMapper.insertUserCoupon(userCoupon);
        if(i1 == 0){
            return R.fail("领取失败");
        }

        System.out.println("领取成功");
        return R.ok("领取成功");
    }

    /**
     * 修改用户优惠券关联
     * 
     * @param userCoupon 用户优惠券关联
     * @return 结果
     */
    @Override
    public int updateUserCoupon(UserCoupon userCoupon)
    {
        return userCouponMapper.updateUserCoupon(userCoupon);
    }

    /**
     * 批量删除用户优惠券关联
     * 
     * @param ucIds 需要删除的用户优惠券关联主键
     * @return 结果
     */
    @Override
    public int deleteUserCouponByUcIds(Long[] ucIds)
    {
        return userCouponMapper.deleteUserCouponByUcIds(ucIds);
    }

    /**
     * 删除用户优惠券关联信息
     * 
     * @param ucId 用户优惠券关联主键
     * @return 结果
     */
    @Override
    public int deleteUserCouponByUcId(Long ucId)
    {
        return userCouponMapper.deleteUserCouponByUcId(ucId);
    }
}
